package com.cucn.ingmall.product.web;

import com.cucn.ingmall.product.entity.CategoryEntity;
import com.cucn.ingmall.product.service.CategoryService;
import com.cucn.ingmall.product.vo.Catalog2VO;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

/**
 * 用户前台首页控制器
 *
 * @author KouChaoJie
 * @since: 2021/12/14 10:20
 */
@Slf4j
@Controller
public class IndexController {
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 首页跳转逻辑及渲染一级分类
     *
     * @param model model
     * @return 跳转逻辑-首页
     */
    @GetMapping(value = {"/", "/index.html"})
    public String indexPage(Model model) {
        //查出所有一级分类
        List<CategoryEntity> categoryList = categoryService.selectLevelOneCategory();
        model.addAttribute("categorys", categoryList);

        return "index";
    }

    /**
     * 将渲染后的二级三级分类数据以json形式传给前端
     * "1":[Catalog2VO]
     *
     * @return 二三级分类的map格式数据
     */
    @GetMapping("index/catalog.json")
    @ResponseBody
    public Map<String, List<Catalog2VO>> getCatalogJson() {
        Map<String, List<Catalog2VO>> map = categoryService.getCatalogJson();
        return map;
    }

    @GetMapping("hello")
    @ResponseBody
    public String hello() {
        RLock lock = redissonClient.getLock("my-lock");
        lock.lock();

        try {
            log.info("成功索取锁:{}", Thread.currentThread().getId());
            Thread.sleep(30000);
        } catch (Exception e) {
        } finally {
            lock.unlock();
            log.info("执行完毕...释放锁:{}", Thread.currentThread().getId());
        }

        return "hello";
    }
}
